package com.tensquare.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import utils.JwtUtil;

import javax.servlet.http.HttpServletRequest;

@Component // 记得加入容器，否则不运行
public class ManagerZuulFilter extends ZuulFilter {

    @Override
    public String filterType() { //过滤器类型
        return FilterConstants.PRE_TYPE; //前置过滤器
    }

    @Override
    public int filterOrder() {
        return 9; // 优先级，距离越小，优先级越高
    }

    @Override
    public boolean shouldFilter() {
        return true; // 是否开启本过滤器 true 表示开启
    }

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public Object run() throws ZuulException {
        System.out.println("manager 后台过滤器");
        // 上下文
        RequestContext currentContext = RequestContext.getCurrentContext();
        // 请求对象
        HttpServletRequest request = currentContext.getRequest();

        // 获取token对象
        String jwtAuthorization = request.getHeader("JwtAuthorization");
        if (jwtAuthorization != null && !"".equals(jwtAuthorization)) {
            if (jwtAuthorization.startsWith("Bearer ")) {
                String token = jwtAuthorization.substring(7);
                // 并与前端协定的开头值一致Bearer
                // 解析token
                try {
                    Claims claims = this.jwtUtil.parseJWT(token);
                    // 提取jwt中的roles自定义值
                    String roles = (String) claims.get("roles");
                    if ("admin".equals(roles)) {
                        // 如果是admin的角色,把头信息转发，并放行
                        currentContext.addZuulRequestHeader("JwtAuthorization", jwtAuthorization);
                        // 放行
                        return null;
                    }
                } catch (Exception e) {
                    // 打印错误，并拦截请求
                    e.printStackTrace();
                    // 拦截，不放行
                    currentContext.setSendZuulResponse(false);
                }
            }
        }

        // 拦截
        currentContext.setSendZuulResponse(false);
        currentContext.setResponseBody("权限不足");
        currentContext.getResponse().setContentType("text/html;charset=utf-8");
        // 设置响应体状态码
        currentContext.setResponseStatusCode(403);
        return null;
    }
}
